package com.fire.market.controller;

import com.fire.component.cache.local.RedisOperate;
import com.fire.component.dto.Response;
import com.fire.component.dto.SingleResponse;
import com.fire.component.extension.Assert;
import com.fire.component.extension.BizCommonError;
import com.fire.component.extension.ExceptionFactory;
import com.fire.market.order.api.request.OrderCreateParam;
import com.fire.market.order.api.result.OrderTokenResult;
import com.fire.market.order.api.service.OrderQueryFrontService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("order/query")
@Api(tags = "订单query服务")
public class OrderQueryController extends BaseController{
    @Reference
    OrderQueryFrontService orderQueryFrontService;

    @PostMapping("/fun_queryPromoToken")
    @ApiOperation(value = "查询订单token", notes = "查询订单token")
    public SingleResponse<String> queryPromoToken(@RequestBody OrderCreateParam param){
        Assert.notNull(param, "param is null");
        return SingleResponse.of(orderQueryFrontService.queryPromoToken(param).getData());
    }

    /**
     * 获取验证码
     * @param response
     * @param userId
     * @return
     */
    @PostMapping("/fun_generateToken/{userId}")
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @ApiImplicitParam(name = "userId", value = "用户Id", required = true, dataType = "String")
    public Response generateToken(HttpServletResponse response, @PathVariable("userId") String userId){
        SingleResponse<OrderTokenResult> orderTokenResultSingleResponse = orderQueryFrontService.generateToken(userId);
        Map<String, Object> map  =  orderTokenResultSingleResponse.getData().getTokenParam();
        try {
            ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", response.getOutputStream());
            RedisOperate.set("verify_code_" + userId, map.get("code"));
        } catch (IOException e) {
            throw ExceptionFactory.bizException(BizCommonError.UNKNOWN_ERROR.getErrCode(),
                    BizCommonError.UNKNOWN_ERROR.getErrMsg());
        }
        return Response.buildSuccess();
    }
}
